<?php

class Kd_Web_Identity {

    protected static $sessionKey = '__identity';
    protected $data = array('roles'=>array(), 'actions'=>array(), 'login'=>FALSE, 'grade'=>'', 'name'=>'', 'id'=>'');

    public function __construct() {
        if(Kd_Web::getSession()->has(self::$sessionKey)){
            $this->data = unserialize(Kd_Web::getSession()->get(self::$sessionKey));
        }
    }

    public function getId() {
        return $this->data['id'];
    }

    public function setId($value) {
        $this->data['id'] = $value;
        return $this;
    }

    public function getName() {
        return $this->data['name'];
    }

    public function setName($value) {
        $this->data['name'] = $value;
        return $this;
    }

    public function isLogin() {
        return $this->data['login'] == TRUE;
    }

    public function getRoles() {
        return $this->data['roles'];
    }

	public function addAction($action){
		if(is_array($action)){
			$this->data['actions'] = array_merge($this->data['actions'], $action);
		}else{
			$this->data['actions'][] = $action;
		}
		return $this;
	}
	
	public function isAllowAction($action){
		return in_array($action, $this->data['actions']);
	}
	
	public function isAllowAnyAction(array $actions){
		foreach($actions as $action){
			if($this->isAllowAction($action)){
				return TRUE;
			}
		}
		
		return FALSE;
	}

    public function addRole($role) {
    	if(is_array($role)){
    		$this->data['roles'] = array_merge($this->data['roles'], $role);
    	}else{
        	$this->data['roles'][] = $role;
    	}
        return $this;
    }

    public function isInRole($code) {
        return in_array($code, $this->data['roles']);
    }

    public function isInAnyRole(array $roleCodes) {
        foreach ($roleCodes as $code) {
            if ($this->isInRole($code)) {
                return TRUE;
            }
        }
        return FALSE;
    }

    public function login() {
        $this->data['login'] = TRUE;
        Kd_Web::getSession()->set(self::$sessionKey, serialize($this->data));
    }

    public function logout() {
        $this->data['login'] = FALSE;
        Kd_Web::getSession()->remove(self::$sessionKey);
    }

}